layui.use(['tree', 'util', 'form'], function(){
    var tree = layui.tree,
        layer = layui.layer,
        $ = layui.jquery,
        form = layui.form;

    //监听提交
    form.on('submit(formDemo)', function(data){
        //layer.msg(JSON.stringify(data.field));
        var doctype = "";
        $("input[type='checkbox']").each(function() {
            if(this.checked) {
                doctype += this.title + ","
            }
        });
        doctype = doctype.substring(0, doctype.length - 1);
        data.field.allowFile = doctype;
        layer.msg(JSON.stringify(data.field));
        return false;
    });

    $.get("/resource/get/tree",function(data){
        tree.render({
            elem: '#test12',
            data: data.data,
            edit: ['add', 'update', 'del'], //操作节点的图标
            operate: function(obj) {
                var type = obj.type; //得到操作类型：add、edit、del
                var data = obj.data; //得到当前节点的数据
                var elem = obj.elem; //得到当前节点元素
                //Ajax 操作
                var id = data.id; //得到节点索引
                if (type === 'add') { //增加节点
                    //返回 key 值
                    return 123;
                } else if (type === 'update') { //修改节点
                    console.log(elem.find('.layui-tree-txt').html()); //得到修改后的内容
                } else if (type === 'del') { //删除节点

                }
            },
            click: function(obj){
                //layer.msg(JSON.stringify(obj.data));
                $("#resource-title").val(obj.data.title);
                $("#resource-path").val(obj.data.path);
                $("#resource-num").val(obj.data.sortNum);
                $("#resource-desc").val(obj.data.desc);
                var items = [];
                if(obj.data.allowFile) {
                    items = obj.data.allowFile.split(",");
                }
                $("input[type='checkbox']").each(function() {
                    $(this).prop("checked",false);
                    if(items.length >= 0) {
                        for(var j = 0; j < items.length; j++) {
                            if(this.title === items[j]) {
                                $(this).prop("checked",true);
                            }
                        }
                    }
                });
                // 必须重新选择
                form ? form.render("checkbox") : null;
            }
        });
    });
});